<template>
  <div v-if="isLoginOrRegisterPage">
    <router-view></router-view>
  </div>
  <div v-else class="app">
    <nav class="nav">
      <router-link to="/home">首页</router-link>
      <router-link to="/cart">购物车</router-link>
      <router-link to="/user">个人中心</router-link>
      <a href="#" @click.prevent="handleLogout">退出登录</a>
    </nav>
    <router-view></router-view>
    <FloatingCart v-if="isLoggedIn" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import FloatingCart from './components/FloatingCart.vue'

const router = useRouter()
const route = useRoute()
const isLoggedIn = ref(false)

const updateLoginStatus = () => {
  isLoggedIn.value = localStorage.getItem('isLoggedIn') === 'true'
}

onMounted(() => {
  updateLoginStatus()
  window.addEventListener('storage', updateLoginStatus)
  window.addEventListener('login-success', updateLoginStatus)
})

onUnmounted(() => {
  window.removeEventListener('storage', updateLoginStatus)
  window.removeEventListener('login-success', updateLoginStatus)
})

const handleLogout = () => {
  localStorage.removeItem('isLoggedIn')
  localStorage.removeItem('username') 
  localStorage.removeItem('userRole')
  localStorage.removeItem('token')
  isLoggedIn.value = false
  window.dispatchEvent(new CustomEvent('auth-change', {
    detail: { isLoggedIn: false, username: '' }
  }))
  router.push('/')
}

const isLoginOrRegisterPage = computed(() => route.path === '/' || route.path === '/login' || route.path === '/register')
</script>

<style>
.app {
  font-family: 'Segoe UI', 'PingFang SC', Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #f8fafc;
}

.nav {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 18px;
  padding: 18px 32px;
  margin-bottom: 30px;
  background: linear-gradient(90deg, #42b983 0%, #6dd5ed 100%);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(66, 185, 131, 0.08);
}

.nav a, .nav .router-link-active {
  color: #fff;
  font-weight: 500;
  font-size: 1.1em;
  text-decoration: none;
  padding: 6px 16px;
  border-radius: 6px;
  transition: background 0.2s, color 0.2s;
}

.nav a.router-link-active, .nav a:hover {
  background: rgba(255,255,255,0.18);
  color: #ffe082;
}

.nav a:last-child {
  margin-left: auto;
  background: #fff;
  color: #42b983;
  font-weight: bold;
  border-radius: 6px;
  padding: 6px 18px;
  transition: background 0.2s, color 0.2s;
}

.nav a:last-child:hover {
  background: #ffe082;
  color: #42b983;
}
</style>
